package com.aabte.design2.behavioral.iterator;

import java.util.Collection;

/**
 * 微信联系人迭代器
 *
 * @author Daniel
 * @version 1.0
 * @date 2020/5/3
 */
public class WeChatIterator implements ProfileIterator {
    private final WeChat weChat;
    private final int profileId;
    private final String type;

    /**
     * 迭代器对象会独立于其他迭代器来对集合进行遍历。因此它必须保存迭代器的状态
     */
    private int currentPosition = 0;
    private Profile[] cache;

    public WeChatIterator(WeChat weChat, int profileId, String type) {
        this.weChat = weChat;
        this.profileId = profileId;
        this.type = type;
    }

    @Override
    public Profile getNext() {
        if (hasMore()) {
            return cache[currentPosition++];
        }
        return null;
    }

    @Override
    public boolean hasMore() {
        lazyInit();
        return currentPosition < cache.length;
    }

    private void lazyInit() {
        if (null == cache) {
            Collection<Profile> profiles = weChat.socialGraphRequest(profileId, type);
            cache = new Profile[profiles.size()];
            profiles.toArray(cache);
        }
    }
}
